package cn.mmko.infrastructure.adapter.port;

import cn.mmko.domain.auth.adapter.port.ILoginPort;
import cn.mmko.infrastructure.gateway.IWeixinApiService;
import cn.mmko.infrastructure.gateway.dto.WeixinQrCodeRequestDTO;
import cn.mmko.infrastructure.gateway.dto.WeixinQrCodeResponseDTO;
import cn.mmko.infrastructure.gateway.dto.WeixinTemplateMessageDTO;
import cn.mmko.infrastructure.gateway.dto.WeixinTokenResponseDTO;
import com.google.common.cache.Cache;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import retrofit2.Call;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class LoginPort implements ILoginPort {
    private static final String WX_ACCESS_TOKEN_KEY = "weixin:access_token:%s";
    private static final String WX_OPENID_KEY = "weixin:openid:%s";
    @Value("${weixin.config.app-id}")
    private String appid;
    @Value("${weixin.config.app-secret}")
    private String appSecret;
    @Value("${weixin.config.template-id}")
    private String template_id;
    @Resource
    private Cache<String, String> weixinAccessToken;
    @Resource
    private IWeixinApiService weixinApiService;
    @Override
    public String createQrCodeTicket() throws IOException {
            String accessToken = weixinAccessToken.getIfPresent(appid);// 获取 accessToken改
//            String accessTokenKey = String.format(WX_ACCESS_TOKEN_KEY, appid);
//          RBucket<String> accessTokenBucket = redissonClient.getBucket(accessTokenKey);
//            String accessToken = accessTokenBucket.get();
            if(null==accessToken){
                Call<WeixinTokenResponseDTO> call = weixinApiService.getToken("client_credential", appid, appSecret);
                WeixinTokenResponseDTO weixinTokenRes = call.execute().body();
                assert weixinTokenRes != null;
                accessToken = weixinTokenRes.getAccess_token();
                weixinAccessToken.put(appid,accessToken);// 缓存accessToken改
//                accessTokenBucket.set(accessToken);
            }
            WeixinQrCodeRequestDTO weixinQrCodeReq = WeixinQrCodeRequestDTO.builder()
                    .expire_seconds(2592000)
                    .action_name(WeixinQrCodeRequestDTO.ActionNameTypeVO.QR_STR_SCENE.getCode())
                    .action_info(WeixinQrCodeRequestDTO.ActionInfo.builder()
                            .scene(WeixinQrCodeRequestDTO.ActionInfo.Scene.builder()
                                    .scene_id(100601)
                                    .build())
                            .build())
                    .build();
            Call<WeixinQrCodeResponseDTO> call= weixinApiService.createQrCode(accessToken, weixinQrCodeReq);
            WeixinQrCodeResponseDTO weixinQrCodeRes = call.execute().body();
            assert null!=weixinQrCodeRes  ;
            return weixinQrCodeRes.getTicket();
    }

    @Override
    public void sendLoginTemplate(String openid) throws IOException {
        //  openidToken.put(ticket,openid);// 缓存openid改
//        RBucket<String> openidBucket = redissonClient.getBucket(String.format(WX_OPENID_KEY,ticket));
//        openidBucket.set(openid);
        // 1. 获取 accessToken 【实际业务场景，按需处理下异常】
          String accessToken = weixinAccessToken.getIfPresent(appid);// 获取 accessToken改
//        String accessTokenKey = String.format(WX_ACCESS_TOKEN_KEY, appid);
//        RBucket<String> accessTokenBucket = redissonClient.getBucket(accessTokenKey);
//        String accessToken = accessTokenBucket.get();
        if (null == accessToken){
            Call<WeixinTokenResponseDTO> call = weixinApiService.getToken("client_credential", appid, appSecret);
            WeixinTokenResponseDTO weixinTokenRes = call.execute().body();
            assert weixinTokenRes != null;
            accessToken = weixinTokenRes.getAccess_token();
            weixinAccessToken.put(appid, accessToken);// 缓存accessToken改
//            accessTokenBucket.set(accessToken);
        }

        // 2. 发送模板消息
        Map<String, Map<String, String>> data = new HashMap<>();
        WeixinTemplateMessageDTO.put(data, WeixinTemplateMessageDTO.TemplateKey.USER, openid);

        WeixinTemplateMessageDTO templateMessageDTO = new WeixinTemplateMessageDTO(openid, template_id);
        templateMessageDTO.setUrl("https://gaga.plus");
        templateMessageDTO.setData(data);

        Call<Void> call = weixinApiService.sendMessage(accessToken, templateMessageDTO);
        call.execute();
    }
}
